import React, { Component } from 'react'
import { Button, Card, Form, Icon, Input, message, Popover, Select, Spin } from 'antd'
import { connect } from 'react-redux'
import { mdLayout } from '../../constant/constant-style'
import { withRouter } from 'react-router-dom'
import STATUS from '../../constant/simple-quiz-status'
import * as actions from '../../actions/simple-coding-quiz'
import SelectTags from '../common/select-tags'
import { getAllStacks } from '../../actions/stack'
import { TwsReactMarkdownEditor } from 'tws-antd'
import { getUploadUrl } from '../../constant/upload-url'
import {convertContent} from '../../constant/lang-util'
import { FormattedMessage } from 'react-intl'

const FormItem = Form.Item
const Option = Select.Option
class AddCodingQuizBody extends Component {
  constructor () {
    super()
    this.state = {
      id: -1,
      repository: '',
      stackId: 0,
      tags: [],
      stackError: '',
      repositoryError: '',
      description: '',
      isShowSpin: false,
      isShowResult: false,
      referenceAnswer: ''
    }
  }

  componentDidMount () {
    this.props.getAllStacks()
  }

  handleDescriptionChange (description) {
    this.setState({description})
  }

  loopLogs () {
    const {status, id} = this.props.simpleCodingQuiz

    if (status === STATUS.PENDING) {
      this.props.getSimpleCodingQuiz(id)
      window.setTimeout(() => this.loopLogs(this.props.simpleCodingQuiz), 1000)
      return
    }

    if (status === STATUS.FAILURE) {
      message.warn(convertContent('出题失败'))
    }
    if (status === STATUS.SUCCESS) {
      message.success(convertContent('出题成功'))
    }
    this.setState({isShowSpin: false})
  }

  handleSubmit (e) {
    e.preventDefault()
    const {tags} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({isShowSpin: true, isShowResult: true})
        values = Object.assign({}, values, {tags})
        this.props.addSimpleCodingQuiz(values, () => { this.loopLogs() })
      }
    })
  }

  changeReferenceAnswer (referenceAnswer) {
    this.setState({referenceAnswer})
  }

  getGuide () {
    return <div>
      <header><FormattedMessage id='简单编程题可以有以下四种创建方式' /></header>
      <ol>
        <li><FormattedMessage id='【无答案，无测试脚本，学员只需要提交repo】repo 包含 master 分支，内容不做任何要求' /></li>
        <li><FormattedMessage id='【有答案，无测试脚本，学员只需要提交repo】repo 需要包含 master 和 answer 分支，内容不做任何要求' /></li>
        <li><FormattedMessage id='【无答案，有测试脚本】repo 需要包含 master ，该分支中需要包含 script.sh 脚本，用于测试答案正确性' /></li>
        <li><FormattedMessage id='【有答案，有测试脚本】repo 需要包含 master 和 answer 分支，该分支中需要包含 script.sh 脚本，用于测试答案正确性' /></li>
      </ol>
    </div>
  }

  render () {
    const {getFieldDecorator} = this.props.form
    const {tags, isShowResult, isShowSpin, description, referenceAnswer} = this.state
    const {simpleCodingQuiz, settings} = this.props

    return <Form onSubmit={this.handleSubmit.bind(this)}>
      <p>
        <a onClick={() => window.history.back()}><Icon type='arrow-left' /><FormattedMessage id='返回上一页' /></a>
      </p>
      <div className='simpleCodingQuiz-guide' style={{color: 'red'}}>
        <Popover content={this.getGuide()} placement='topLeft' >
          <Icon type='question-circle' style={{fontSize: '20'}} />
          <FormattedMessage id='使用说明' />
        </Popover>
      </div>
      <FormItem label={<FormattedMessage id='名称' />} {...mdLayout}>
        {getFieldDecorator('title',
          {rules: [{required: true, message: <FormattedMessage id='请填写题目名称' />}]})(<Input />)}
      </FormItem>

      <FormItem label={<FormattedMessage id='题目描述' />}{...mdLayout}>
        {getFieldDecorator('description',
          {rules: [{required: true, message: <FormattedMessage id='请填写题目描述' />}]})(
            <TwsReactMarkdownEditor
              action={getUploadUrl(settings.appContextPath)}
              value={description}
              onChange={this.handleDescriptionChange.bind(this)} />)}
      </FormItem>

      <FormItem label='stack' {...mdLayout}>
        {getFieldDecorator('stackId', {
          rules: [{required: true, message: <FormattedMessage id='请选择技术栈' />}]
        })(
          <Select
            placeholder={<FormattedMessage id='请选择技术栈' />}>
            {this.props.stacks.map(stack => <Option key={stack.id} value={stack.id}>{stack.title}</Option>)}
          </Select>
        )}
      </FormItem>

      <FormItem label='repository' {...mdLayout}>
        {getFieldDecorator('definitionRepo', {
          rules: [{
            required: true,
            pattern: new RegExp(/^(?:https:\/\/)?(?:github\.com\/)(?:[^ ]+)(?:\/)(?:[^ ]+).git$/),
            message: <FormattedMessage id='请填入github地址!' />
          }]
        })(
          <Input className='min-width' />
        )}
      </FormItem>

      <FormItem label={<FormattedMessage id='分支' />} {...mdLayout}>
        {getFieldDecorator('branch',
          {rules: [{required: false, message: <FormattedMessage id='分支' />}]})(<Input placeholder='master' />)}
      </FormItem>
      <SelectTags
        addTags={(tags) => this.setState({tags})}
        currentTags={tags} />
      <FormItem
        {...mdLayout}
        label={<FormattedMessage id='参考答案' />}
      >
        {getFieldDecorator('referenceAnswer',
          {rules: [{required: false, message: <FormattedMessage id='请填写参考答案' />}]})(
            <TwsReactMarkdownEditor value={referenceAnswer}
              action={getUploadUrl(settings.appContextPath)}
              onChange={this.changeReferenceAnswer.bind(this)} />)}

      </FormItem>
      <FormItem
        wrapperCol={{offset: 9}}
      >
        <Button type='primary' htmlType='submit'>
          <FormattedMessage id='添加' />
        </Button>
      </FormItem>
      {isShowResult
        ? <Card style={{width: '100%'}}>
          {isShowSpin ? <Spin /> : ''}
          <div>{simpleCodingQuiz.jobMessage || <FormattedMessage id='正在排队中' />}</div>
        </Card>
        : ''}
    </Form>
  }
}

const mapStateToProps = ({simpleCodingQuiz, stackData, settings}) => ({
  settings,
  simpleCodingQuiz,
  stacks: stackData.stacks.content
})

const mapDispatchToProps = dispatch => ({
  addSimpleCodingQuiz: (quiz, callback) => dispatch(actions.addSimpleCodingQuiz(quiz, callback)),
  getSimpleCodingQuiz: (quizId) => dispatch(actions.getSimpleCodingQuiz(quizId)),
  getAllStacks: () => dispatch(getAllStacks())
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(AddCodingQuizBody)))
